package com.charm.xft.bill.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.charm.xft.bill.entity.*;
import com.charm.xft.bill.mapper.XftBillMapper;
import com.charm.xft.bill.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ujmp.core.util.StringUtil;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2023-03-27
 */
@Service
@Slf4j
public class XftBillServiceImpl extends ServiceImpl<XftBillMapper, XftBill> implements IXftBillService {

    @Autowired
    IXftBillDetailService billDetailService;

    @Autowired
    IXftBillExpService expService;
    @Autowired
    IXftBillCustomFieldValueService customFieldValueService;
    @Autowired
    IXftBillInvoiceCloudObjectService invoiceCloudObjectService;
    @Autowired
    IXftBillExpCaseAprHistoryService aprHistoryService;
    @Autowired
    IXftBillExpCustomFieldValueService expCustomFieldValueService;
    @Autowired
    IXftBillInvoiceItemService invoiceItemService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public XftBill saveBillAllEntityByJSONObject(JSONObject jb, String memember) {
        XftBill xftBill = new XftBill();
        xftBill.setId(jb.getJSONObject("billInfo").getStr("billId"));
        xftBill.setCreateTime(LocalDateTime.now());
        xftBill.setJsonData(jb.toJSONString(0));
        xftBill.setApplyTime(jb.getJSONObject("billInfo").getLocalDateTime("applyTim", LocalDateTime.MIN));
        xftBill.setAttachFileDownloadStatus("0");

        BillExtDetailInfoDtosBean billExtDetailInfoDtosBean = jb.toBean(BillExtDetailInfoDtosBean.class);

        //删除所有历史数据

        if (xftBill.getId() != null) {
            long count = this.count(new LambdaQueryWrapper<XftBill>().eq(XftBill::getId, xftBill.getId()));
            if (count > 0) {
                xftBill.setAttachFileDownloadStatus("-1");
            }

            deleteALLBillById(xftBill.getId());
            save(xftBill);
            saveBillDetail(billExtDetailInfoDtosBean, memember);
            saveExp(xftBill.getId(), billExtDetailInfoDtosBean);
            saveAprHistory(billExtDetailInfoDtosBean);
            log.info("订单【{}】处理完毕", xftBill.getId());
        }

        return xftBill;
    }


    private void deleteALLBillById(String id) {
        this.remove(new LambdaQueryWrapper<XftBill>().eq(XftBill::getId, id));
        customFieldValueService.remove(new LambdaQueryWrapper<XftBillCustomFieldValue>().eq(XftBillCustomFieldValue::getCffBillId, id));
        aprHistoryService.remove(new LambdaQueryWrapper<XftBillExpCaseAprHistory>().eq(XftBillExpCaseAprHistory::getBillId, id));
        expCustomFieldValueService.remove(new LambdaQueryWrapper<XftBillExpCustomFieldValue>().eq(XftBillExpCustomFieldValue::getXffBillId, id));
        expService.remove(new LambdaQueryWrapper<XftBillExp>().eq(XftBillExp::getExpBillId, id));
        invoiceCloudObjectService.remove(new LambdaQueryWrapper<XftBillInvoiceCloudObject>().eq(XftBillInvoiceCloudObject::getBillId, id));
        invoiceItemService.remove(new LambdaQueryWrapper<XftBillInvoiceItem>().eq(XftBillInvoiceItem::getBillId, id));
        billDetailService.remove(new LambdaQueryWrapper<XftBillDetail>().eq(XftBillDetail::getBillId, id));

    }

    private void saveBillCustomField(BillExtDetailInfoDtosBean billExtDetailInfoDtosBean) {
        if (CollectionUtil.isNotEmpty(billExtDetailInfoDtosBean.getBillInfo().getCustomFieldValues())) {
            for (XftBillCustomFieldValue customFieldValue : billExtDetailInfoDtosBean.getBillInfo().getCustomFieldValues()) {
                customFieldValue.setCffBillId(billExtDetailInfoDtosBean.getBillInfo().getBillId());
                customFieldValue.setCustomFieldId(IdUtil.getSnowflakeNextIdStr());
                try {
                    JSONArray objects = JSONUtil.parseArray(customFieldValue.getCustomFieldValue());
                    if (objects.size() > 0) {
                        for (Object object : objects) {
                            JSONObject obj = (JSONObject) object;
                            String id = obj.getStr("id");
                            String name = obj.getStr("name");
                            customFieldValue.setCustomFieldValueName(name);
                            customFieldValue.setCustomFiledValueId(id);
                            customFieldValueService.save(customFieldValue);
                        }
                    } else {
                        customFieldValueService.save(customFieldValue);
                    }
                } catch (Exception e) {
                    customFieldValueService.save(customFieldValue);
                }

            }
        }
    }

    private void saveAprHistory(BillExtDetailInfoDtosBean billExtDetailInfoDtosBean) {

        if (billExtDetailInfoDtosBean.getAprHisList() != null && billExtDetailInfoDtosBean.getAprHisList().size() > 0) {
            List<XftBillExpCaseAprHistory> aprHisList = billExtDetailInfoDtosBean.getAprHisList();
            List<XftBillExpCaseAprHistory> collect = aprHisList.stream().filter(i -> i.getSeqId() != null).map(i -> {
                        i.setCreateTime(LocalDateTime.now());
                        return i;
                    }
            ).collect(Collectors.toList());
            if(collect.size() > 0) {
                aprHistoryService.saveOrUpdateBatch(collect);

            }

        }

}

    private void saveExp(String billID, BillExtDetailInfoDtosBean billExtDetailInfoDtosBean) {
        if (billExtDetailInfoDtosBean.getExpList() != null && billExtDetailInfoDtosBean.getExpList().size() > 0) {
            List<ExpListBean> expList = billExtDetailInfoDtosBean.getExpList();
            for (ExpListBean expListBean : expList) {
                XftBillExp xftBillExp = new XftBillExp();
                BeanUtil.copyProperties(expListBean, xftBillExp);
                xftBillExp.setExpBillId(billID);
                expListBean.setBillId(Long.parseLong(billID));
                xftBillExp.setExpId(IdUtil.getSnowflakeNextIdStr());
                saveCertification(xftBillExp.getExpId(), expListBean);
                saveExpCustomField(xftBillExp.getExpId(), expListBean);
                expService.save(xftBillExp);
            }

        }
    }

    private void saveExpCustomField(String seqId, ExpListBean expListBean) {
        if (CollectionUtil.isNotEmpty(expListBean.getCustomFieldValues())) {
            List<XftBillExpCustomFieldValue> customFieldValues = expListBean.getCustomFieldValues();
            for (XftBillExpCustomFieldValue customFieldValue : customFieldValues) {
                customFieldValue.setXffBillId(String.valueOf(expListBean.getBillId()));
                customFieldValue.setXffExpId(seqId);
                customFieldValue.setCustomFieldId(IdUtil.getSnowflakeNextIdStr());
                try {
                    JSONArray objects = JSONUtil.parseArray(customFieldValue.getCustomFieldValue());
                    if (objects.size() > 0) {
                        for (Object object : objects) {
                            JSONObject obj = (JSONObject) object;
                            String id = obj.getStr("id");
                            String name = obj.getStr("name");
                            customFieldValue.setCustomFieldValueName(name);
                            customFieldValue.setCustomFiledValueId(id);
                            expCustomFieldValueService.save(customFieldValue);
                        }
                    } else {
                        expCustomFieldValueService.save(customFieldValue);
                    }
                } catch (Exception e) {
                    expCustomFieldValueService.save(customFieldValue);
                }
            }
        }
    }

    private void saveCertification(String expId, ExpListBean expListBean) {
        for (InvoiceCloudCertificatesBean invoiceCloudCertificate : expListBean.getCertificate().getInvoiceCloudCertificates()) {
            XftBillInvoiceCloudObject xftBillInvoiceCloudObject = new XftBillInvoiceCloudObject();
            BeanUtil.copyProperties(invoiceCloudCertificate, xftBillInvoiceCloudObject);
            xftBillInvoiceCloudObject.setBillId(String.valueOf(expListBean.getBillId()));
            xftBillInvoiceCloudObject.setExpId(expId);
            if (StrUtil.isBlank(xftBillInvoiceCloudObject.getInvoiceNumber())) {
                if (StrUtil.isNotBlank(xftBillInvoiceCloudObject.getTrafficEcode())) {
                    xftBillInvoiceCloudObject.setInvoiceNumber(xftBillInvoiceCloudObject.getTrafficEcode());
                }
            }
            invoiceCloudObjectService.save(xftBillInvoiceCloudObject);

            List<XftBillInvoiceItem> invoiceDetailList = invoiceCloudCertificate.getInvoiceDetailList();
            for (XftBillInvoiceItem xftBillInvoiceItem : invoiceDetailList) {
                xftBillInvoiceItem.setBillId(String.valueOf(expListBean.getBillId()));
                xftBillInvoiceItem.setExpId(expId);
                invoiceItemService.save(xftBillInvoiceItem);
            }
        }
    }


    private void saveBillDetail(BillExtDetailInfoDtosBean billExtDetailInfoDtosBean, String memember) {
        BillBean billInfo = billExtDetailInfoDtosBean.getBillInfo();
        XftBillDetail xftBillDetail = new XftBillDetail();
        BeanUtil.copyProperties(billInfo, xftBillDetail);
        xftBillDetail.setBillId(billInfo.getBillId());
        xftBillDetail.setCreateTime(LocalDateTime.now());
        xftBillDetail.setUserNumber(memember);
        billDetailService.save(xftBillDetail);
        saveBillCustomField(billExtDetailInfoDtosBean);
    }
}
